#!/usr/bin/env python
# $Id: ouisearch.py df54dec975f4 2012/09/09 20:22:40 pgurumur $
# Copyright (c) 2012 Prabhu Gurumurthy <pgurumur@gmail.com>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__  = "$Revision: df54dec975f4 $"
__author__   = "$Author: pgurumur $"
__modified__ = "$Date: 2012-09-09 20:22:40Z $"

import HTMLParser
import optparse
import sys
import urllib2

from venya.lib import cmdparser
from venya.lib import stdlib

class MACParser(HTMLParser.HTMLParser):
   def __init__(self, *args):
      HTMLParser.HTMLParser.__init__(self)
      self._data = {}
      self._tags = []
      self._htmltag = []

      for ix in args:
         self._htmltag.append(ix)

   def handle_starttag(self, tag, attrs):
      if tag in self._htmltag:
         self._tags.append(tag)

   def handle_endtag(self, tag):
      if tag in self._htmltag:
         self._tags.pop()

   def handle_data(self, data):
      if len(self._tags) > 0:
         self._data[self._tags[-1]] = data

   def __getattr__(self, attr):
      retval = None
      if attr.lower() in self._data.keys():
         retval = self._data[attr].strip()

      return retval

class ouisearch(cmdparser.GetOpt):
   option_list = (
         optparse.make_option("-m", "--mac", type = "str",
            help = "MAC Address to search in OUI database", dest = "mac"),
         ) + cmdparser.GetOpt.option_list

   def __init__(self, **keywords):
      super(self.__class__, self).__init__(**keywords)
      self._url = "http://standards.ieee.org/cgi-bin/ouisearch"
      self._mac = None
      self._conn = None

   def handle(self):
      (options, args) = self.parse()

      if options.mac:
         addr = None
         if options.mac.find(".") != -1:
            addr = options.mac.replace(".", "")
         elif options.mac.find(":") != -1:
            addr = options.mac.replace(":", "")

         mac = "-".join(options.mac.split(":")[0:3])
         self._url = "%s?%s" %(self._url, mac)
         parser = MACParser("pre")

         try:
            self._conn = urllib2.urlopen(self._url)
         except urllib2.URLError as err:
            self.error(err)
         else:
            parser.feed(self._conn.read())
            if parser.pre is not None:
               temp = parser.pre.split("\n")[1]
               temp = temp.split("\t")
               print ("mac: %s, manufacturer: %s" %(options.mac, temp[-1]))
            else:
               print ("cannot find manufacturer for mac %s" %options.mac)

if __name__ == "__main__":
   ouis = None
   try:
      ouis = ouisearch(version = 1.0, args = sys.argv, usage = "mac")
      if len(ouis) <= 1:
         ouis.printhelp()
      else:
         ouis.handle()
   except cmdparser.GetOptError as message:
      print message
      sys.exit(1)
